package repository

import (
	"dataaysn/internal/model"
	"dataaysn/pkg/response"

	"gorm.io/gorm"
)

type HospitalRepository interface {
	CreateHospital(hospital *model.Hospital) (*response.Response, error)
	GetHospital(id string) (*response.Response, error)
	UpdateHospital(hospital *model.Hospital) (*response.Response, error)
	DeleteHospital(id string) (*response.Response, error)
	ListHospitals(hospital *model.Hospital, page, pageSize int) (*response.Response, error)
}
type gormHospitalRepository struct {
	db *gorm.DB
}

func NewGormHospitalRepository(db *gorm.DB) HospitalRepository {
	return &gormHospitalRepository{db: db}
}

func (r *gormHospitalRepository) CreateHospital(hospital *model.Hospital) (*response.Response, error) {
	if err := r.db.Create(hospital).Error; err != nil {
		return nil, err
	}
	return response.Success(hospital), nil
}

func (r *gormHospitalRepository) GetHospital(id string) (*response.Response, error) {
	var hospital model.Hospital
	if err := r.db.First(&hospital, id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, response.NotFound("医院不存在")
		}
		return nil, err
	}
	return response.Success(hospital), nil
}

func (r *gormHospitalRepository) UpdateHospital(hospital *model.Hospital) (*response.Response, error) {
	if err := r.db.Save(hospital).Error; err != nil {
		return nil, err
	}
	return response.Success(hospital), nil
}

func (r *gormHospitalRepository) DeleteHospital(id string) (*response.Response, error) {
	if err := r.db.Delete(&model.Hospital{}, id).Error; err != nil {
		return nil, err
	}
	return response.Success(nil), nil
}

func (r *gormHospitalRepository) ListHospitals(hospital *model.Hospital, page, pageSize int) (*response.Response, error) {
	var hospitals []model.Hospital
	var total int64
	db := r.db.Model(&model.Hospital{}).Debug()
	// 多条件动态查询
	if hospital.HospitalCode != "" {
		db = db.Where("hospital_code = ?", hospital.HospitalCode)
	}
	if hospital.HospitalName != "" {
		db = db.Where("hospital_name LIKE ?", "%"+hospital.HospitalName+"%")
	}
	if err := db.Count(&total).Error; err != nil {
		return nil, err
	}
	if err := db.Offset((page - 1) * pageSize).Limit(pageSize).Find(&hospitals).Error; err != nil {
		return nil, err
	}
	pageResult := &response.PageResult{
		List:     hospitals,
		Total:    total,
		Page:     page,
		PageSize: pageSize,
	}
	return response.Success(pageResult), nil
}
